package br.com.mundodaprata.store.testes;

import java.text.ParseException;

public class CPFGenerator {

   
   public static String get() {  
      String number = String.valueOf( NumberUtil.random( 9 ) );  
      
      number += getDigito(number);
      number += getDigito(number);  
      
      if ( !new CPFValidator().isValid(number) ){
         number = get();
      }
      
      return number;
   }

   private static int getDigito(String number) {
      int soma = 0;
      int fator = number.length()+1;
      //Para calcular o primeiro digito verificador  
      for(int i =0; i<number.length();i++){  
         soma += NumberUtil.parseInteger( Character.toString( number.charAt(i) ) ) * fator;  
         fator--;  
      }  
      int resto = soma % 11;  
      return (resto < 2) ? 0 : (11 - resto);
   }  

   
   public static String getMasked(){
      return formatCpf( get() );
   }
   
   public static String formatCpf( String textCpf ){
      return formatText( textCpf, "###.###.###-##" );
   }

   public static String formatCnpj(String cnpj) {
      return formatText( cnpj, "##.###.###/####-##" );
   }

   public static String formatText(String text, String mask){
      try{
         MaskFormatter mf = new MaskFormatter(mask);
         mf.setValueContainsLiteralCharacters(false);
         return mf.valueToString(text);
      }
      catch (ParseException e) {
         return text;
      }
   }
}